package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.pojo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-9-26 16:39
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        //分页查询  刘增辉
        PageHelper.startPage(page,rows);

        Example example = new Example(Brand.class);

        Example.Criteria criteria = example.createCriteria();

        Example.Criteria criteria1 = example.createCriteria();

        if (StringUtils.isNotBlank(key)){
            criteria1.andLike("name","%"+key+"%");
            criteria.andEqualTo("letter",key);
        }

        example.or(criteria1);

        if (StringUtils.isNotBlank(sortBy)) {
            // 排序 select * from tb_brand where xxx order by name DESC
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }

        //执行查询，把查询结果直接强转
        Page<Brand> brandList = (Page<Brand>) brandMapper.selectByExample(example);



        return  new PageResult<>(brandList.getTotal(), brandList);
    }

    public void deleteById(Long id) {
        System.out.println("删除：id = " + id);
    }

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {

        //保存brand，会发生主键回显
        this.brandMapper.insertSelective(brand);

        for (Long cid : cids) {
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }

    public Brand queryBrandById(Long brandId) {
        return brandMapper.selectByPrimaryKey(brandId);
    }

    public List<Brand> queryBrandByCategory(Long cid) {

        return this.brandMapper.queryBrandByCategory(cid);
    }

    public List<Brand> queryBrandByIds(List<Long> ids) {

        return this.brandMapper.selectByIdList(ids);
    }
}
